package com.xnyzc.lhy.resource.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.component.amap.HttpClientPool;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.GpsUtil;
import com.xnyzc.lhy.resource.entity.amap.AmapGouldHistoryGps;
import com.xnyzc.lhy.resource.entity.amap.AmapGouldResult;
import com.xnyzc.lhy.resource.entity.amap.GpsHistoryInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: huxuekuo
 * @Date: 2019-07-29 15:49
 * @Description: 封装高德地图
 */
@Data
@Slf4j
@Component
public class GouldMapUtil {

    /**
     * 高德 Web API
     */
    public static String webKey;

    @Value("${global.amap.webKey}")
    public void setWebKey(String amapWebKey) {
        webKey = amapWebKey;
    }

    /**
     * 测距接口
     */
    private static final String DISTANCE_URL = "http://restapi.amap.com/v3/distance?";

    private static final String TSAPI = "https://tsapi.amap.com/v1/track/terminal/trsearch?";

    /**
     * 删除轨迹
     * 删除一条轨迹，轨迹删除后无法进行恢复。
     */
    private static final String DELTRACK = "https://tsapi.amap.com/v1/track/trace/delete";


    /**
     * 上传点位
     * 轨迹点上传（单点、批量）
     */
    private static final String UPLOADTRACK = "https://tsapi.amap.com/v1/track/point/upload";


    /**
     * 测距接口--起点参数
     */
    private static final String ORIGINS = "origins=";

    /**
     * 测距接口--起点参数
     */
    private static final String TYPE = "type=";

    /**
     * 测距接口--终点参数
     */
    private static final String DESTINATION = "destination=";


    /**
     * 字符串拼接
     */
    private static final String AND = "&";

    private static final String PATH_URL = "http://restapi.amap.com/v3/direction/driving?";

    //    查询历史轨迹 orderNo: ZFJC201911320870875621,  服务ID: 84017, 轨迹ID: 200, 终端ID: 225490196, 开始时间: 1573890360223 结束时间: 1573890469777
//    public static void main(String[] args) {
//        AmapGouldHistoryGps amapGouldHistoryGps = historyGps(84017L, 225490196L, 580L, 1573898317994L, System.currentTimeMillis(), 1);
//        System.out.println(amapGouldHistoryGps);
//    }

    /**
     * 获取猎鹰历史轨迹
     *
     * @param sid       服务ID
     * @param trid      GPSID
     * @param tid       终端ID
     * @param starttime 开始时间(时间戳)
     * @param endtime   结束时间(时间戳)
     * @param page      当前页
     * @return
     */
    public static AmapGouldHistoryGps historyGps(Long sid, Long trid, Long tid, Long starttime, Long endtime, int page, Integer type) {
        StringBuffer sb = new StringBuffer();
        sb.append(TSAPI);
        sb.append("key=" + webKey);
        sb.append("&sid=" + sid);
        sb.append("&trid=" + trid);
        sb.append("&tid=" + tid);
        sb.append("&starttime=" + starttime);
        sb.append("&endtime=" + endtime);
        if (type.equals(0)) {
            sb.append("&correction=denoise=1,mapmatch=1,attribute=1,threshold=0,mode=driving");
            sb.append("&recoup=1");
            sb.append("&gap=100");
        } else {
            sb.append("&correction=denoise=1,mapmatch=0,attribute=0,threshold=0,mode=driving");
        }
        sb.append("&page=" + page);
        sb.append("&pagesize=999");
        HttpGet get = new HttpGet(sb.toString());
        HttpClient httpClient = HttpClientBuilder.create().build();
        try {
            //发送请求
            HttpResponse execute = httpClient.execute(get);
            if (responseStatus(execute.getStatusLine())) {
                HttpEntity entity = execute.getEntity();
                StringBuilder strJson = getJson(entity);
                //如果内容不为空,将内存转换为JSON返回
                if (StringUtils.isNotEmpty(strJson.toString())) {
                    return JSON.parseObject(strJson.toString(), AmapGouldHistoryGps.class);
                }
            }
        } catch (IOException e) {
            throw PangException.create(EErrorCode.c500);
        }
        throw PangException.create(EErrorCode.apiRstError);
    }

    /**
     * 删除轨迹
     *
     * @param sid  服务ID
     * @param trid 轨迹ID
     * @param tid  终端ID
     * @return
     */
    public static boolean deleteGpsHistorys(Long sid, Long trid, Long tid) {
        // 设置请求参数
        StringBuffer sb = new StringBuffer();
        sb.append("key=" + webKey);
        sb.append("&sid=" + sid);
        sb.append("&tid=" + tid);
        sb.append("&trid=" + trid);
        try {
            // POST请求设置参数
            HttpPost post = new HttpPost(DELTRACK);
            StringEntity stringEntity = new StringEntity(sb.toString());//param参数，可以为"key1=value1&key2=value2"的一串字符串
            stringEntity.setContentType("application/x-www-form-urlencoded");
            post.setEntity(stringEntity);
            // 发送请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse httpResponse = httpClient.execute(post);
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            System.out.println(result);
            if (CheckUtil.strIsNotEmpty(result)) {
                // 判断是否存在errcode并且是成功
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.containsKey("errcode") && jsonObject.getLong("errcode").equals(10000)) {
                    return true;
                }
            }
            log.info("删除轨迹信息 服务ID:[{}],轨迹ID:[{}],终端ID:[{}] 返回信息:[{}]", sid, trid, tid, result);
        } catch (Exception e) {
            // 打印错误栈 ClassName.class
            log.error("", e);
        }
        return false;
    }

    public static boolean uploadTrack(Long sid, Long tid, Long trid, List<Object> infoList) {
        // 设置请求参数
        StringBuffer sb = new StringBuffer();
        sb.append("key=" + webKey);
        sb.append("&sid=" + sid);
        sb.append("&tid=" + tid);
        sb.append("&trid=" + trid);
        sb.append("&points=" + JSON.toJSONString(infoList));
        try {
            // POST请求设置参数
            HttpPost post = new HttpPost(UPLOADTRACK);
            StringEntity stringEntity = new StringEntity(sb.toString());//param参数，可以为"key1=value1&key2=value2"的一串字符串
            stringEntity.setContentType("application/x-www-form-urlencoded");
            post.setEntity(stringEntity);
            // 发送请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse httpResponse = httpClient.execute(post);
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            System.out.println(result);
            if (CheckUtil.strIsNotEmpty(result)) {
                // 判断是否存在errcode并且是成功
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.containsKey("errcode") && jsonObject.getLong("errcode").equals(10000)) {
                    return true;
                }
            }
            log.info("删除轨迹信息 服务ID:[{}],轨迹ID:[{}],终端ID:[{}] 返回信息:[{}]", sid, trid, tid, result);
        } catch (Exception e) {
            // 打印错误栈 ClassName.class
            log.error("轨迹上传失败！", e);
        }
        return false;
    }

//    public static void main(String[] args) {
//        //-- 84017  227207385 2560
//        deleteGpsHistorys(84017L, 2560L, 227207385L);
//    }

    public static StringBuilder getJson(HttpEntity entity) {
        //获取返回内容,将返回内容转换为JSON数据
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(entity.getContent());
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            StringBuilder strJson = new StringBuilder();
            //从文件中按字节读取内容，到文件尾部时read方法将返回-1
            while ((bytesRead = bis.read(buffer)) != -1) {
                //将读取的字节转为字符串对象
                strJson.append(new String(buffer, 0, bytesRead));
            }
            log.info("获取到的高德返回的信息: {}", strJson);
            return strJson;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 测两个点位之间的距离
     *
     * @param startPoint 起点例如(116.413731,39.979324)
     * @param endPoint   终点(116.413731,39.979324)
     * @return
     */
    public static AmapGouldResult getDistance(String startPoint, String endPoint) {
        AmapGouldResult amapGouldResult = null;
        if (GpsUtil.checkItudePoint(startPoint) && GpsUtil.checkItudePoint(endPoint)) {
            //拼接参数
            StringBuffer stringBuffer = new StringBuffer(DISTANCE_URL);
            stringBuffer.append("key=" + webKey);
            stringBuffer.append(AND + ORIGINS + startPoint);
            stringBuffer.append(AND + DESTINATION + endPoint);
            HttpGet get = new HttpGet(stringBuffer.toString());
            amapGouldResult = readContent(get);

        }
        return amapGouldResult;
    }


    /**
     * 路径规划
     *
     * @param startPoint
     * @param endPoint
     * @return
     */
    public static AmapGouldResult getPath(String startPoint, String endPoint) {
        //设置参数,详见高德接口文档
        StringBuilder stringBuilder = new StringBuilder(PATH_URL);
        stringBuilder.append("key=" + GouldMapUtils.getRandomWebKey());
        stringBuilder.append("&origin=" + startPoint);
        stringBuilder.append("&destination=" + endPoint);
        stringBuilder.append("&originid=");
        stringBuilder.append("&destinationid=");
        stringBuilder.append("&extensions=base");
        stringBuilder.append("&strategy=");
        stringBuilder.append("&waypoints=");
        stringBuilder.append("&avoidpolygons=");
        stringBuilder.append("&avoidroad=");
        HttpGet get = new HttpGet(stringBuilder.toString());
        AmapGouldResult amapGouldResult = readContent(get);
        return amapGouldResult;
    }

    /**
     * 获取请求状态
     *
     * @param status
     * @return
     */
    private static boolean responseStatus(StatusLine status) {
        return status.getStatusCode() == 200 ? true : false;
    }

    /**
     * 获取请求内容
     *
     * @param get 内容流
     * @return
     */
    private static AmapGouldResult readContent(HttpGet get) {
        log.info("httpClient请求：{}", get.getURI());

        long startTime = System.currentTimeMillis();
        HttpClient client = HttpClientPool.getClient();
        try (CloseableHttpResponse execute = (CloseableHttpResponse) client.execute(get)) {
            // 处理响应内容....
            if (responseStatus(execute.getStatusLine())) {
                HttpEntity entity = execute.getEntity();
                StringBuilder strJson = getJson(entity);
                //如果内容不为空,将内存转换为JSON返回
                if (StringUtils.isNotEmpty(strJson.toString())) {
                    AmapGouldResult amapGouldResult1 = JSON.parseObject(strJson.toString(), AmapGouldResult.class);
                    log.info("httpClient 请求耗时：{}", System.currentTimeMillis() - startTime);
                    return amapGouldResult1;
                }
            }
        } catch (ClientProtocolException e) {
            log.error("httpClient请求异常：{}",e);
            throw PangException.create(EErrorCode.c500);
        } catch (IOException e) {
            log.error("httpClient请求异常：{}",e);
            throw PangException.create(EErrorCode.c500);
        }
        throw PangException.create(EErrorCode.apiRstError);
    }

    /**
     * 获取速度最快的公里数与时间段
     *
     * @return
     */
    public static Map<String, Integer> getStrategy(String startPoint, String endPoint) {
        Map<String, Integer> result = new HashMap<>();
        log.info("起始终止经纬度为：{}||{}", startPoint, endPoint);
        AmapGouldResult.RouteBean route = getPath(startPoint, endPoint).getRoute();
        List<AmapGouldResult.RouteBean.PathsBean> paths = route.getPaths();
        int size = paths.size();
        for (int i = 0; i < size; i++) {
            AmapGouldResult.RouteBean.PathsBean path = paths.get(i);
            //找出速度最快的路径
            if (path.getStrategy().equals(MessageConstant.GOULD_STRATEGY_SPEED)) {
                //设置里程,和时间
                result.put(EGould.gouldDistance.getValue(), Integer.valueOf(path.getDistance()));
                result.put(EGould.gouldDuration.getValue(), Integer.valueOf(path.getDuration()));
                return result;
            }
        }
        return result;
    }

    public static double getDistance(String startLng, String startLat, String endLng, String endLat) {
        //判断轨迹是否为空
        if (CheckUtil.strIsEmpty(startLng, startLat, endLng, endLat)) {
            throw PangException.create(EErrorCode.gpsError);
        }
        Map<String, Integer> strategy = getStrategy(startLng + "," + startLat, endLng + "," + endLat);
        Integer integer = strategy.get(EGould.gouldDistance.getValue());
        return BigDecimal.valueOf(Math.rint(Double.valueOf(integer / 100) / 10)).setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

    /**
     * 获取两点之间驾车距离(文字版)
     *
     * @param startPoint
     * @param endPoint
     * @return
     */
    public static HashMap<String, String> getDistanceAndDuration(String startPoint, String endPoint) {
        HashMap<String, String> result = new HashMap<>();
        Map<String, Integer> strategy = getStrategy(startPoint, endPoint);
        //转换为KM
        Integer integer = strategy.get(EGould.gouldDistance.getValue());
        //小于等于500米,显示米
        if (integer <= 500) {
            result.put(EGould.gouldDistance.getValue(), integer + MessageConstant.METER);
        } else {
            result.put(EGould.gouldDistance.getValue(), new BigDecimal(Math.rint(Double.valueOf(strategy.get(EGould.gouldDistance.getValue()) / 100) / 10)).setScale(2, BigDecimal.ROUND_HALF_DOWN) + MessageConstant.KILOMETRE);

        }
        result.put(EGould.gouldDuration.getValue(), new BigDecimal(Math.rint(Double.valueOf(strategy.get(EGould.gouldDuration.getValue())) / 60)).setScale(1, BigDecimal.ROUND_HALF_DOWN) + MessageConstant.MINUTES);
        result.put(EGould.gouldDurationKm.getValue(), String.valueOf(new BigDecimal(Math.rint(Double.valueOf(strategy.get(EGould.gouldDuration.getValue())) / 60)).setScale(1, BigDecimal.ROUND_HALF_DOWN)));
        result.put(EGould.gouldIntDuration.getValue(), String.valueOf(new BigDecimal(Math.rint(Double.valueOf(strategy.get(EGould.gouldDuration.getValue())) / 60)).setScale(0, BigDecimal.ROUND_UP)));
        return result;
    }

    /**
     * 测两个点位之间的直线距离
     *
     * @return
     */
    public static Integer getLineDistance(String startLng, String startLat, String endLng, String endLat) {
        Integer distance = 0;
        String startPoint = startLng + "," + startLat;
        String endPoint = endLng + "," + endLat;
        AmapGouldResult amapGouldResult = null;
        //拼接参数
        StringBuffer stringBuffer = new StringBuffer(DISTANCE_URL);
        stringBuffer.append("key=" + webKey);
        // 直线距离
        stringBuffer.append(AND + TYPE + ParameterEnum.ZERO.getTypeName());
        stringBuffer.append(AND + ORIGINS + startPoint);
        stringBuffer.append(AND + DESTINATION + endPoint);
        HttpGet get = new HttpGet(stringBuffer.toString());
        amapGouldResult = readContent(get);
        if (CheckUtil.objIsNotEmpty(amapGouldResult)) {
            if (CheckUtil.objIsNotEmpty(amapGouldResult.getResults())) {
                List<AmapGouldResult.Results> resultsList = amapGouldResult.getResults();
                if (CheckUtil.objIsNotEmpty(resultsList.get(0).getDistance())) {
                    distance = Integer.valueOf(resultsList.get(0).getDistance());
                }
            }
        }
        return distance;
    }
}
